package com.github.xiaoymin.map.util;

import com.github.xiaoymin.map.response.baidu.BaiduGenCoderResponse;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.xml.sax.InputSource;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: ots4-ota-adapter
 * @Package: com.lishiots.cloud.utils
 * @ClassName: XmlUtils
 * @Author: wanglf
 * @Description: xml工具类
 * @Date: 2020/6/25 13:46
 * @Version: 1.0
 */
public class XmlUtils {

    public static Map<String, String> doXMLParse(String strxml)
            throws JDOMException, IOException {
        if (null == strxml || "".equals(strxml)) {
            return null;
        }
        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
        Map<String, String> m = new HashMap<String, String>();
        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List<Element> list = root.getChildren();
        Iterator<Element> it = list.iterator();
        while (it.hasNext()) {
            Element e = (Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = getChildrenText(children);
            }

            m.put(k, v);
        }
        return m;
    }
    /**
     * 获取子结点的xml
     * @param children
     * @return String
     */
    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if(!children.isEmpty()) {
            Iterator it = children.iterator();
            while(it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if(!list.isEmpty()) {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }

        return sb.toString();
    }

    /***
     * 告诉微信服务器，我收到信息了，不要在调用回调action了
     * @param return_code
     * @param return_msg
     * @return
     */
    public static String setXML(String return_code, String return_msg){
        return "<xml><return_code><![CDATA[" + return_code
                + "]]></return_code><return_msg><![CDATA[" + return_msg
                + "]]></return_msg></xml>";
    }

    /**
     * description: 解析微信通知xml
     *
     * @param xml
     *
     * @return
     *
     * @see
     */
    public static Map parseXmlToList(String xml)
    {
        Map retMap = new HashMap();
        try
        {
            StringReader read = new StringReader(xml);
            // 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
            InputSource source = new InputSource(read);
            // 创建一个新的SAXBuilder
            SAXBuilder sb = new SAXBuilder();
            // 通过输入源构造一个Document
            Document doc = (Document) sb.build(source);
            Element root = doc.getRootElement();// 指向根节点
            List<Element> es = root.getChildren();
            if (es != null && es.size() != 0)
            {
                for (Element element : es)
                {
                    retMap.put(element.getName(), element.getValue());
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return retMap;
    }

    /**

     * 将String类型的xml转换成对象

     */

    public static Object convertXmlStrToObject(Class<?> clazz, String xmlStr) {

        Object xmlObject = null;

        try {

            JAXBContext context = JAXBContext.newInstance(clazz);

            // 进行将Xml转成对象的核心接口

            Unmarshaller unmarshal = context.createUnmarshaller();

            StringReader sr = new StringReader(xmlStr);

            xmlObject = unmarshal.unmarshal(sr);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return xmlObject;

    }

    /**
     * 将对象转换为 xml字符串
     */

    public static String convertObjectToXml(Class<?> clazz,Object obj) {

        String xmlObj = null;

        try {

            JAXBContext context = JAXBContext.newInstance(clazz);
            Marshaller marshaller = context.createMarshaller();

            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            marshaller.marshal(obj, baos);
            xmlObj = new String(baos.toByteArray());

        } catch (Exception e) {

            e.printStackTrace();

        }

        return xmlObj;

    }

    public static void main(String[] args) {
       String xml ="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
               "<GeocoderSearchResponse>\n" +
               "\t<status>0</status>\n" +
               "\t<result>\n" +
               "\t\t<location>\n" +
               "\t\t\t<lng>115.197255</lng>\n" +
               "\t\t\t<lat>31.869642985</lat>\n" +
               "\t\t</location>\n" +
               "\t\t<formatted_address>河南省信阳市商城县</formatted_address>\n" +
               "\t\t<business/>\n" +
               "\t\t<addressComponent>\n" +
               "\t\t\t<country>中国</country>\n" +
               "\t\t\t<country_code>0</country_code>\n" +
               "\t\t\t<country_code_iso>CHN</country_code_iso>\n" +
               "\t\t\t<country_code_iso2>CN</country_code_iso2>\n" +
               "\t\t\t<province>河南省</province>\n" +
               "\t\t\t<city>信阳市</city>\n" +
               "\t\t\t<city_level>2</city_level>\n" +
               "\t\t\t<district>商城县</district>\n" +
               "\t\t\t<town/>\n" +
               "\t\t\t<town_code/>\n" +
               "\t\t\t<adcode>411524</adcode>\n" +
               "\t\t\t<street/>\n" +
               "\t\t\t<street_number/>\n" +
               "\t\t\t<direction/>\n" +
               "\t\t\t<distance/>\n" +
               "\t\t</addressComponent>\n" +
               "\t\t<pois/>\n" +
               "\t\t<roads/>\n" +
               "\t\t<poiRegions/>\n" +
               "\t\t<sematic_description/>\n" +
               "\t\t<cityCode>214</cityCode>\n" +
               "\t</result>\n" +
               "</GeocoderSearchResponse>";
        BaiduGenCoderResponse baiduGenCoderResponse = (BaiduGenCoderResponse) XmlUtils.convertXmlStrToObject(BaiduGenCoderResponse.class, xml);
        System.out.println(baiduGenCoderResponse.toString());


    }

}
